<template>
  <el-dialog class="assign-role"
             title="分配角色"
             :visible="showRoleDialog"
             width="40%"
             @close="close"
             @open="open">
    <!-- 组件事件open -->
    <!-- 复选框 -->
    <el-checkbox-group v-model="checkList"
                       v-loading="loading">
      <el-checkbox v-for="item in list"
                   :key="item.id"
                   :label="item.id">
        {{item.name}}
      </el-checkbox>

    </el-checkbox-group>
    <template #footer>
      <el-button type="primary"
                 size="small"
                 @click="assign">确定</el-button>
      <el-button size="small"
                 @click="close">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetail } from '@/api/user'
import { assignRole } from '@/api/employess'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 选中的角色
      checkList: [],
      // 所有角色的列表
      list: [],
      loading: false
    }
  },
  methods: {
    // 关闭弹窗
    close() {
      this.$emit('update:showRoleDialog', false)
    },
    // 代替了created 不直接进页面渲染 点击了角色在渲染
    async open() {
      this.loading = true
      await Promise.all([this.getRoleList(), this.getUserDetail()])
      this.loading = false
      // this.getRoleList()
      // this.getUserDetail() // 获取当前用户的已经分配的角色
    },
    // 数据回显
    async getRoleList() {
      const data = await getRoleList(1, 10)
      this.list = data.rows
    },
    async getUserDetail() {
      const data = await getUserDetail(this.userId)
      // console.log(data)
      this.checkList = data.roleIds
    },
    // 确定 保证
    async assign() {
      await assignRole(this.userId, this.checkList)
      this.$message.success('分配角色成功')
      this.$emit('update:showRoleDialog', false)


    }
  }
}
</script>

<style>
</style>
